<template>
  <div class="sql-web3-container">
    <!-- 头部 -->
    <header class="sql-web3-header">
      <div class="header-content">
        <div class="header-logo-container">
          <div class="logo-icon-container">
            <i class="fa fa-shield text-white text-xl"></i>
          </div>
          <div>
            <h1 class="site-title">高级SQL注入靶场</h1>
            <p class="site-subtitle">http://localhost:8080/new_env/flaw_sql12/458djn221A.php</p>
          </div>

        </div>
        <div class="header-badge-container">
          <div class="header-badge">
            专家级 · WAF绕过
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="content-wrapper">
        <!-- 页面标题和说明 -->
        <div class="page-header">
          <h2 class="page-title">高级SQL注入绕过练习</h2>
          <p class="page-description">
            本练习包含WAF防护、严格过滤和预处理语句环境，需要使用高级注入技术才能获取FLAG。
          </p>
        </div>

        <!-- 安全状态指示器 -->
        <div class="security-status-container">
          <div class="security-status-item">
            <div class="status-indicator active"></div>
            <span>WAF防护已启用</span>
          </div>
          <div class="security-status-item">
            <div class="status-indicator active"></div>
            <span>严格输入过滤</span>
          </div>
          <div class="security-status-item">
            <div class="status-indicator active"></div>
            <span>预处理语句模拟</span>
          </div>
          <div class="security-status-item">
            <div class="status-indicator warning"></div>
            <span>异常检测系统</span>
          </div>
        </div>

        <!-- 多场景选项卡 -->
        <div class="scenario-tabs">
          <div class="tabs-container">
            <button
                @click="activeScenario = 'login'"
                :class="activeScenario === 'login' ? 'tab-button active' : 'tab-button'"
            >
              登录表单
            </button>
            <button
                @click="activeScenario = 'search'"
                :class="activeScenario === 'search' ? 'tab-button active' : 'tab-button'"
            >
              搜索功能
            </button>
            <button
                @click="activeScenario = 'json'"
                :class="activeScenario === 'json' ? 'tab-button active' : 'tab-button'"
            >
              JSON API
            </button>
            <button
                @click="activeScenario = 'register'"
                :class="activeScenario === 'register' ? 'tab-button active' : 'tab-button'"
            >
              用户注册
            </button>
          </div>
        </div>

        <!-- 主功能卡片 -->
        <div class="main-card">
          <!-- 登录表单场景 -->
          <div v-if="activeScenario === 'login'">
            <div class="scenario-header">
              <div class="scenario-icon-container" style="background-color: rgba(225, 29, 72, 0.2); border: 1px solid rgba(225, 29, 72, 0.3);">
                <i class="fa fa-lock text-rose-400"></i>
              </div>
              <h3 class="scenario-title">管理员登录</h3>
            </div>

            <form @submit.prevent="submitLogin">
              <div class="form-group">
                <label for="login-username" class="form-label">用户名</label>
                <div class="input-wrapper">
                  <div class="input-icon">
                    <i class="fa fa-user text-gray-500"></i>
                  </div>
                  <input
                      type="text"
                      id="login-username"
                      v-model="loginUsername"
                      class="form-input"
                      placeholder="管理员用户名"
                  >
                </div>
              </div>

              <div class="form-group">
                <label for="login-password" class="form-label">密码</label>
                <div class="input-wrapper">
                  <div class="input-icon">
                    <i class="fa fa-key text-gray-500"></i>
                  </div>
                  <input
                      type="password"
                      id="login-password"
                      v-model="loginPassword"
                      class="form-input"
                      placeholder="管理员密码"
                  >
                </div>
              </div>

              <div class="form-group">
                <button
                    type="submit"
                    class="submit-button"
                >
                  <i class="fa fa-sign-in"></i>
                  <span>登录</span>
                </button>
              </div>
            </form>
          </div>

          <!-- 搜索功能场景 -->
          <div v-if="activeScenario === 'search'">
            <div class="scenario-header">
              <div class="scenario-icon-container" style="background-color: rgba(4, 120, 87, 0.2); border: 1px solid rgba(4, 120, 87, 0.3);">
                <i class="fa fa-search text-emerald-400"></i>
              </div>
              <h3 class="scenario-title">数据搜索</h3>
            </div>

            <form @submit.prevent="submitSearch">
              <div class="form-group">
                <label for="search-term" class="form-label">搜索关键词</label>
                <div class="input-wrapper">
                  <div class="input-icon">
                    <i class="fa fa-search text-gray-500"></i>
                  </div>
                  <input
                      type="text"
                      id="search-term"
                      v-model="searchTerm"
                      class="form-input"
                      placeholder="搜索产品或信息"
                  >
                </div>
              </div>

              <div class="form-group">
                <button
                    type="submit"
                    class="submit-button"
                >
                  <i class="fa fa-search"></i>
                  <span>搜索</span>
                </button>
              </div>
            </form>
          </div>

          <!-- JSON API场景 -->
          <div v-if="activeScenario === 'json'">
            <div class="scenario-header">
              <div class="scenario-icon-container" style="background-color: rgba(202, 138, 4, 0.2); border: 1px solid rgba(202, 138, 4, 0.3);">
                <i class="fa fa-code text-amber-400"></i>
              </div>
              <h3 class="scenario-title">JSON API请求</h3>
            </div>

            <form @submit.prevent="submitJson">
              <div class="form-group">
                <label for="json-payload" class="form-label">JSON payload</label>
                <textarea
                    id="json-payload"
                    v-model="jsonPayload"
                    class="form-textarea"
                    placeholder='例如: {"user":"admin", "pass":"password"}'
                ></textarea>
              </div>

              <div class="form-group">
                <button
                    type="submit"
                    class="submit-button"
                >
                  <i class="fa fa-paper-plane"></i>
                  <span>发送请求</span>
                </button>
              </div>
            </form>
          </div>

          <!-- 用户注册场景 -->
          <div v-if="activeScenario === 'register'">
            <div class="scenario-header">
              <div class="scenario-icon-container" style="background-color: rgba(29, 78, 216, 0.2); border: 1px solid rgba(29, 78, 216, 0.3);">
                <i class="fa fa-user-plus text-blue-400"></i>
              </div>
              <h3 class="scenario-title">用户注册</h3>
            </div>

            <form @submit.prevent="submitRegister">
              <div class="form-group">
                <label for="reg-username" class="form-label">用户名</label>
                <input
                    type="text"
                    id="reg-username"
                    v-model="regUsername"
                    class="form-input"
                    placeholder="创建用户名"
                >
              </div>

              <div class="form-group">
                <label for="reg-password" class="form-label">密码</label>
                <input
                    type="password"
                    id="reg-password"
                    v-model="regPassword"
                    class="form-input"
                    placeholder="创建密码"
                >
              </div>

              <div class="form-group">
                <button
                    type="submit"
                    class="submit-button"
                >
                  <i class="fa fa-user-plus"></i>
                  <span>注册</span>
                </button>
              </div>
            </form>
          </div>

          <!-- WAF日志 -->
          <div v-if="wafLog.length > 0" class="waf-log-container">
            <div class="waf-log-header">
              <i class="fa fa-shield text-yellow-500 mr-2"></i>
              <p>WAF防护日志</p>
            </div>
            <ul class="waf-log-list">
              <li v-for="(log, index) in wafLog" :key="index" class="waf-log-item">
                <span :class="`log-severity ${log.severity}`" v-if="log.severity === 'high'">[高风险] </span>
                <span :class="`log-severity ${log.severity}`" v-if="log.severity === 'medium'">[中风险] </span>
                <span :class="`log-severity ${log.severity}`" v-if="log.severity === 'low'">[低风险] </span>
                {{ log.message }}
              </li>
            </ul>
          </div>

          <!-- 执行信息显示 -->
          <div v-if="executionInfo" class="execution-info-container">
            <div class="execution-info-header">
              <i class="fa fa-code text-gray-500 mr-2 text-sm"></i>
              <p>执行信息</p>
            </div>
            <pre class="execution-info-content">{{ executionInfo }}</pre>
          </div>

          <!-- 结果显示区域 -->
          <div v-if="showResult" class="result-container">
            <!-- 成功获取FLAG -->
            <div v-if="result.success" class="success-result">
              <div class="success-content">
                <div class="success-icon-container">
                  <i class="fa fa-flag text-rose-400 text-2xl"></i>
                </div>
                <h4 class="success-title">恭喜！成功绕过高级防护并获取FLAG！</h4>
                <div class="flag-display">
                  {{ result.flag }}
                </div>
                <p class="success-message">
                  <i class="fa fa-check-circle"></i>
                  <span>你成功突破了高级SQL注入防护机制！</span>
                </p>
              </div>
            </div>

            <!-- 操作结果 -->
            <div v-if="!result.success && result.message" class="info-result">
              <div class="info-content">
                <div class="info-icon-container">
                  <i class="fa fa-info-circle text-blue-500"></i>
                </div>
                <div>
                  <h4 class="info-title">操作结果</h4>
                  <p class="info-message">{{ result.message }}</p>
                </div>
              </div>
            </div>

            <!-- 拦截/失败结果 -->
            <div v-if="!result.success && result.error" class="error-result">
              <div class="error-content">
                <div class="error-icon-container">
                  <i class="fa fa-exclamation-circle text-red-500"></i>
                </div>
                <div>
                  <h4 class="error-title">操作失败</h4>
                  <p class="error-message">{{ result.error }}</p>

                  <div v-if="result.isBlocked" class="blocked-warning">
                    <p>⚠️ 检测到可疑活动，已触发WAF防护</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 提示区域 -->
        <div class="hints-container">
          <div class="hints-header">
            <div class="hints-icon-container">
              <i class="fa fa-lightbulb-o text-yellow-400"></i>
            </div>
            <h3 class="hints-title">高级绕过技术提示</h3>
          </div>

          <div class="hints-content">
            <div class="hints-section">
              <h4 class="hints-section-title">防护机制:</h4>
              <ul class="hints-list">
                <li class="hint-item">Web应用防火墙(WAF)规则集</li>
                <li class="hint-item">严格的输入验证和过滤</li>
                <li class="hint-item">部分场景使用预处理语句模拟</li>
                <li class="hint-item">异常行为检测</li>
                <li class="hint-item">多场景不同防护策略</li>
              </ul>
            </div>

            <div class="hints-section">
              <h4 class="hints-section-title">尝试这些高级技术:</h4>
              <p class="hint-text">时间盲注 (适用于搜索场景)、布尔盲注 (适用于搜索场景)、堆叠查询 (适用于特定场景)、二次注入 (先注册后登录)、非常规字符绕过</p>
            </div>
          </div>
        </div>
      </div>
    </main>


  </div>
</template>

<script>
export default {
  data() {
    return {
      // 场景管理
      activeScenario: 'login',

      // 登录场景数据
      loginUsername: '',
      loginPassword: '',

      // 搜索场景数据
      searchTerm: '',

      // JSON API场景数据
      jsonPayload: '{"username":"user", "password":"pass"}',

      // 注册场景数据
      regUsername: '',
      regPassword: '',

      // 结果和日志
      showResult: false,
      result: {},
      wafLog: [],
      executionInfo: '',

      // 存储已注册的用户名（用于二次注入模拟）
      registeredUsers: []
    };
  },
  methods: {
    // 重置状态
    resetState() {
      this.showResult = false;
      this.result = {};
      this.wafLog = [];
      this.executionInfo = '';
    },

    // 添加WAF日志
    addWafLog(message, severity = 'medium') {
      this.wafLog.push({ message, severity });
    },

    // 高级WAF过滤模拟
    advancedWafFilter(input) {
      // 基础关键字检测（大小写不敏感）
      const basicKeywords = ['OR', 'AND', 'UNION', 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER', 'EXEC', 'SLEEP', 'WAITFOR', 'DELAY'];
      const keywordRegex = new RegExp(`\\b(${basicKeywords.join('|')})\\b`, 'i');

      if (keywordRegex.test(input)) {
        const matched = input.match(keywordRegex);
        this.addWafLog(`检测到敏感关键字: ${matched[0]}`, 'high');
        return { blocked: true, reason: `检测到敏感关键字: ${matched[0]}` };
      }

      // 检测常见注入模式
      const injectionPatterns = [
        /['";]\/\*/,
        /\/\*.*\*\//,
        /union.*select/i,
        /sleep\(\d+\)/i,
        /if\(.*\)/i,
        /benchmark\(/i,
        /char\(/i
      ];

      for (const pattern of injectionPatterns) {
        if (pattern.test(input)) {
          this.addWafLog(`检测到可疑注入模式: ${pattern.toString()}`, 'high');
          return { blocked: true, reason: '检测到可疑注入模式' };
        }
      }

      // 空格替代字符检测（低风险警告，但不完全拦截）
      const spaceAlternatives = ['%0a', '%09', '%0d', '%20', '+', '/**/'];
      for (const alt of spaceAlternatives) {
        if (input.includes(alt) || input.includes(decodeURIComponent(alt))) {
          this.addWafLog(`检测到可能的空格替代字符: ${alt}`, 'low');
        }
      }

      // 特殊字符检测
      const specialChars = ["'", '"', ';', '--', '#', '='];
      for (const char of specialChars) {
        if (input.includes(char)) {
          this.addWafLog(`检测到特殊字符: ${char}`, 'medium');
        }
      }

      return { blocked: false };
    },

    // 登录表单处理
    submitLogin() {
      this.resetState();

      // 应用WAF过滤
      const usernameCheck = this.advancedWafFilter(this.loginUsername);
      const passwordCheck = this.advancedWafFilter(this.loginPassword);

      if (usernameCheck.blocked || passwordCheck.blocked) {
        this.showResult = true;
        this.result = {
          success: false,
          error: usernameCheck.blocked ? usernameCheck.reason : passwordCheck.reason,
          isBlocked: true
        };
        return;
      }

      // 预处理语句模拟（部分防护）
      this.executionInfo = `执行预处理查询:
SELECT * FROM users WHERE username = ? AND password = ?
参数: ('${this.loginUsername}', '${this.loginPassword}')`;

      // 检测二次注入（如果用户名是之前注册的恶意用户）
      if (this.registeredUsers.includes(this.loginUsername) && this.loginUsername.includes("'")) {
        this.showResult = true;
        this.result = {
          success: true,
          flag: 'FLAG-『二次注入』'
        };
        return;
      }

      // 正常登录检查
      if (this.loginUsername === 'admin' && this.loginPassword === 'ultrasecret') {
        this.showResult = true;
        this.result = {
          success: true,
          flag: 'FLAG-『正常登录』'
        };
      } else {
        this.showResult = true;
        this.result = {
          success: false,
          error: '用户名或密码不正确'
        };
      }
    },

    // 搜索功能处理
    submitSearch() {
      this.resetState();

      // 应用WAF过滤（搜索场景防护较弱，允许部分绕过）
      const check = this.advancedWafFilter(this.searchTerm);

      // 搜索场景允许时间盲注和布尔盲注通过
      const isTimeBased = this.searchTerm.includes('SLEEP') || this.searchTerm.includes('sleep');
      const isBooleanBased = this.searchTerm.includes('LENGTH') || this.searchTerm.includes('length');

      if (check.blocked && !isTimeBased && !isBooleanBased) {
        this.showResult = true;
        this.result = {
          success: false,
          error: check.reason,
          isBlocked: true
        };
        return;
      }

      // 模拟搜索查询执行
      let query = `SELECT * FROM products WHERE name LIKE '%${this.searchTerm}%'`;

      // 模拟时间盲注延迟
      if (isTimeBased) {
        this.executionInfo = `执行查询: ${query}
注意: 检测到可能的时间盲注，模拟延迟响应...`;

        // 模拟延迟
        setTimeout(() => {
          this.showResult = true;
          if (this.searchTerm.includes('ASCII(SUBSTR(database(),1,1))>100')) {
            this.result = {
              success: true,
              flag: 'FLAG-『时间盲注延迟』'
            };
          } else {
            this.result = {
              success: false,
              message: '搜索完成，但未找到匹配结果'
            };
          }
        }, 3000);
        return;
      }

      // 处理布尔盲注
      if (isBooleanBased) {
        this.executionInfo = `执行查询: ${query}`;
        this.showResult = true;

        if (this.searchTerm.includes('LENGTH(database())=8')) {
          this.result = {
            success: true,
            flag: 'FLAG-『布尔盲注』'
          };
        } else {
          this.result = {
            success: false,
            message: '搜索完成，但未找到匹配结果'
          };
        }
        return;
      }

      // 普通搜索
      this.executionInfo = `执行查询: ${query}`;
      this.showResult = true;
      this.result = {
        success: false,
        message: `搜索完成，找到 ${Math.floor(Math.random() * 5)} 个匹配结果`
      };
    },

    // JSON API处理
    submitJson() {
      this.resetState();

      try {
        // 尝试解析JSON
        const json = JSON.parse(this.jsonPayload);

        // 应用WAF过滤
        const check = this.advancedWafFilter(this.jsonPayload);
        if (check.blocked) {
          this.showResult = true;
          this.result = {
            success: false,
            error: check.reason,
            isBlocked: true
          };
          return;
        }

        // 模拟JSON处理
        this.executionInfo = `处理JSON请求:
${JSON.stringify(json, null, 2)}

执行查询:
SELECT * FROM users WHERE username = '${json.username}' AND password = '${json.password}'`;

        // 检测JSON注入
        if (json.username && json.username.includes("'") && json.username.includes('--')) {
          this.showResult = true;
          this.result = {
            success: true,
            flag: 'FLAG-『JSON注入』'
          };
        } else {
          this.showResult = true;
          this.result = {
            success: false,
            message: 'API请求已处理，未找到匹配用户'
          };
        }
      } catch (e) {
        this.showResult = true;
        this.result = {
          success: false,
          error: '无效的JSON格式'
        };
      }
    },

    // 用户注册处理（二次注入准备）
    submitRegister() {
      this.resetState();

      // 应用WAF过滤（注册场景过滤较弱，允许特殊字符）
      const check = this.advancedWafFilter(this.regUsername);

      // 注册场景允许存储带有注入 payload 的用户名
      if (check.blocked) {
        this.addWafLog('宽松模式：允许注册包含特殊字符的用户名', 'low');
        // 不阻断，仅记录
      }

      // 模拟注册处理
      this.executionInfo = `执行注册:
INSERT INTO users (username, password) VALUES ('${this.regUsername}', '${this.regPassword}')`;

      // 存储注册的用户名（用于后续二次注入）
      this.registeredUsers.push(this.regUsername);

      this.showResult = true;
      this.result = {
        success: false,
        message: `用户 "${this.regUsername}" 已成功注册，请尝试登录`
      };
    }
  }
};
</script>

<style scoped lang="css" src="@/assets/styles/sqlweb3.css"></style>
